package cn.bone.springcloud.controller;

import cn.bone.springcloud.base.bean.CommonResult;
import cn.bone.springcloud.bean.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {

    // 写死的服务调用地址
//    private static final String PAYMENT_URL = "http://127.0.0.1:8001";

    // 微服务的服务调用地址
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;



    @RequestMapping("/consumer/get")
    public CommonResult get(Integer id){
        String url = PAYMENT_URL + "/get?id={1}";
        return restTemplate.getForObject(url, CommonResult.class, id);
    }

    @RequestMapping("/consumer/create")
    public CommonResult create(Payment payment){
        String url = PAYMENT_URL + "/create";
        log.info("order serial : {}", payment.getSerial());
        CommonResult result = restTemplate.postForObject(url, payment, CommonResult.class);
        log.info("create result: {}", result);
        return result;
    }

    @RequestMapping("/consumer/add")
    public CommonResult add(String serial){

        String url = PAYMENT_URL + "/add";
        log.info("order serial: {}", serial);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("serial", serial);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        return restTemplate.postForObject(url,request,CommonResult.class);
    }
}
